from rest_framework.exceptions import ValidationError
from rest_framework import serializers
from django_redis import get_redis_connection
from api.serializer.validator import phone_validator


class MessageSerializer(serializers.Serializer):
    phone = serializers.CharField(label="手机号", validators=[phone_validator])


class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField(label="手机号", validators=[phone_validator, ])
    code = serializers.CharField(label="验证码", error_messages={'blank': "验证码不能为空"})
    nickname = serializers.CharField(label="用户名", max_length=32)
    avatar = serializers.CharField(label="用户头像")
    wx_code = serializers.CharField(label="微信openid", max_length=32, read_only=True)

    def validate_code(self, attrs):
        if len(attrs) != 4:
            raise ValidationError('短信格式错误')
        if not attrs.isdecimal():
            raise ValidationError('短信格式错误')
        phone = self.initial_data.get('phone')
        conn = get_redis_connection()
        code = conn.get(phone)

        if not code:
            raise ValidationError('验证码已过期,请获取重新获取')
        if attrs != code.decode('utf-8'):
            raise ValidationError('验证码错误')
        return attrs
